﻿using DataModels.Dto;
using DataModels.Dto.AuthCore;
using Jayrock.Json;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using open_api_sdk_csharp.com.chinaums.open.api;
using open_api_sdk_csharp.com.chinaums.open.api.constants;
using open_api_sdk_csharp.com.chinaums.open.api.internals.utils;
using open_api_sdk_csharp.com.chinaums.open.api.internals.utils.http;
using open_api_sdk_csharp.response;
using Services.AuthCore;
using Services.WorkOrder;
using System;
using System.Net;
using System.Text.RegularExpressions;
using Utils;

namespace PropertyManagementWebApi.Controllers.AuthCore
{
    public class unapyController(UserService userService) : BaseController
    {
        protected readonly UserService _userService = userService;


        #region 支付
        /// <summary>
        /// 异步接收微信支付结果通知的回调地址接口
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public  void CallbackAdressAsynchronouslyWeixinPay()
        {
            
        }
        // 配置参数
        //private const string UnionappId = "10037e6f6a4e6da4016a66ed122d0011";
        //private const string UnionApiKey = "d7ed6a5cc25146b392cfb7b71cabf911";// 你的银联API密钥";
        //private const string UnionMerId = "898201612345678";// 你的银联商户号";
        //private const string UnionTid = "88880001";//你的银联终端号";

        // 生产环境
        private const string UnionappId = "8a81c1be8e80494d018e9d791b9f00b7";
        private const string UnionApiKey = "05c7090add594d10ba10813cd9623bf3";// 你的银联API密钥";
        private const string UnionMerId = "89842016513DERH";// 898201612345678";// 你的银联商户号";
        private const string UnionTid = "D85RQJMF";// ""88880001""; 你的银联终端号";
        private const string UnionUnifiedOrderUrl = "https://api-mop.chinaums.com/v1/netpay/wx/unified-order";

        private const string UnionUnifiedOrderUrltest = "https://test-api-open.chinaums.com/v1/netpay/wx/unified-order";
        private const string WeChatAppId = "wx8a6175dea7b02e1c";// "你的小程序AppId";
        private const string WeChatMchId = "";// 你的微信商户号";
        private const string WeChatApiKey = "2aeff3035d9f845a9c760f84ef36fb48";// 你的微信API密钥";
        private const string NotifyUrl = "https://qiaosui.net/wyApi25/";

       
        //{"orderNo":"AOL72202507291437221084670000000","totalFee":"1","body":"","notifyUrl":"","openId":"o_MGv7esCUSUmSppqDGdtpPiYvSE"}
        // 订单号 327M20220419111222

        /// <summary>
        /// 银联小程序下单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult UnionMiniProgramOrder([FromBody] OrderRequest request)
        {
            string url = UnionUnifiedOrderUrl;

            ConfigBean configBean = new ConfigBean();
            OpenApiContext context = new OpenApiContext();
            
            // 创建主请求对象
            var unionPayRequest = new UnionPayRequest
            {
                RequestTimestamp =Convert.ToDateTime( DateTime.Now.ToString("yyyy-MM-dd HH:dd:ss")),
                MerOrderId = request.OrderNo,
                Mid = UnionMerId,
                Tid = UnionTid ,
                TotalAmount = request.TotalAmount, //* 
                SubAppId = WeChatAppId, //小程序id  *
                TradeType = "MINI", // *
                SubOpenId = request.OpenId, //openid *
                MsgId = "001",
                SrcReserve = "test",
                InstMid = "MINIDEFAULT",

                // 商品信息列表
                Goods = new List<GoodsInfo>
                    {
                        new GoodsInfo
                        {
                            Unit = "个",
                            SubMerchantId = "988460101800201",
                            SubOrderAmount = "100",
                            Quantity = "10",
                            GoodsId = "001",
                            Price = "1",
                            GoodsCategory = "food meterial",
                            Discount = "5",
                            Body = "two eggs",
                            GoodsName = "鸡蛋",
                            MerOrderId = "dd20220419111222"
                        }
                    },

                AttachedData = null,
                ExpireTime = Convert.ToDateTime(DateTime.Now.AddHours(2).ToString("yyyy-MM-dd HH:dd:ss")),
                GoodsTag = null,
                OrderDesc = "测试",
                OriginalAmount = "10",
                ProductId = "002",
                DivisionFlag = "true",
                AsynDivisionFlag = "true",
                PlatformAmount = "1",

                NotifyUrl = NotifyUrl,
                SecureTransaction = "false",
                UserId = null,
                LimitCreditCard = "false",
                InstallmentNumber = "3",
                Name = "张*三",
                Mobile = "131****3453",
                CertType = "IDENTITY_CARD",
                CertNo = "110101********9008",
                FixBuyer = "false",

                // 商户返回参数
                RetCommParams = new RetCommParams
                {
                    VehicleNo = "",
                    FoodOrderType = "pre_order",
                    ParkId = ""
                },

                FeeRatio = "5",
                CostSubsidy = "false",
                PreauthTransaction = "false"
            };
            context.StartTime = DateTime.Now.ToFileTime();
            context.RequestId = Guid.NewGuid().ToString("N");
            string version = url.Split("/")[3];
            context.OpenServUrl = Regex.Split(url, version, RegexOptions.IgnoreCase)[0];
            context.ApiServiceUrl = url;
            context.Version = version;
            context.AppId = UnionappId;
            context.AppKey = UnionApiKey;
            context.ConfigBean = configBean;
            context.ServiceCode = Regex.Split(url, version, RegexOptions.IgnoreCase)[1];
            TokenResponse tokenResponse = TokenUtils.getToken(context);
            context.CurrentToken = tokenResponse;
            string rr = HttpTransport.Instance.doPost(context, JsonConvert.SerializeObject(unionPayRequest, Formatting.Indented));
            Console.WriteLine(rr);

            return Ok(rr);
        }


        /// <summary>
        /// 银联小程序下单 自动生成版
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UnionMiniProgramOrder11([FromBody] OrderRequest request)
        {
            var unionPay = new UnionPayHelper(UnionMerId, UnionApiKey, UnionUnifiedOrderUrl, NotifyUrl);
            var response = await unionPay.MiniProgramOrder(
                orderNo: request.OrderNo,
                totalAmount:Convert.ToDecimal( request.TotalAmount),
                subject: request.Subject,
                openId: request.OpenId
            );

            if (response.code == "SUCCESS")
            {
                return Ok(new { success = true, data = response.result });
            }
            return BadRequest(new { success = false, message = response.msg });
        }

        /// <summary>
        /// 微信小程序下单
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> WeChatMiniProgramOrder([FromBody] OrderRequest request)
        {
            // 微信金额单位为分，需转换
            var totalFee = (int)(Convert.ToDecimal( request.TotalAmount) * 100);

            var weChatPay = new WeChatPayHelper(WeChatAppId, WeChatMchId, WeChatApiKey, NotifyUrl);
            var response = await weChatPay.MiniProgramUnifiedOrder(
                orderNo: request.OrderNo,
                totalFee: totalFee,
                body: request.Subject,
                openId: request.OpenId
            );

            if (response.ReturnCode == "SUCCESS" && response.ResultCode == "SUCCESS")
            {
                // 生成小程序调起支付的参数
                var payParams = GenerateWeChatPayParams(response.PrepayId);
                return Ok(new { success = true, data = payParams });
            }
            return BadRequest(new { success = false, message = response.ErrCodeDes ?? response.ReturnMsg });
        }

        /// <summary>
        /// 生成微信小程序支付参数
        /// </summary>
        private Dictionary<string, string> GenerateWeChatPayParams(string prepayId)
        {
            var nonceStr = Guid.NewGuid().ToString().Replace("-", "");
            var timeStamp = ((DateTimeOffset)DateTime.Now).ToUnixTimeSeconds().ToString();
            var package = $"prepay_id={prepayId}";
            var signType = "MD5";

            // 生成签名
            var signParams = new SortedDictionary<string, string>
                    {
                        {"appId", WeChatAppId},
                        {"timeStamp", timeStamp},
                        {"nonceStr", nonceStr},
                        {"package", package},
                        {"signType", signType}
                    };

            var sign = new WeChatPayHelper(WeChatAppId, WeChatMchId, WeChatApiKey, NotifyUrl)
                .GenerateSign(signParams);

            return new Dictionary<string, string>
                    {
                        {"appId", WeChatAppId},
                        {"timeStamp", timeStamp},
                        {"nonceStr", nonceStr},
                        {"package", package},
                        {"signType", signType},
                        {"paySign", sign}
                    };
        }

        #endregion

    }

    /// <summary>
    /// 订单请求参数
    /// </summary>
    public class OrderRequest
    {
        public string OrderNo { get; set; } // 商户订单号
        public string TotalAmount { get; set; } // 订单金额(分)
        public string Subject { get; set; } // 商品描述
        public string OpenId { get; set; } // 用户标识(银联/微信的openid)
    }
}
